package fr.labri.macchiato.framework.business.service;

import java.util.ArrayList;
import java.util.List;

import fr.labri.macchiato.framework.business.finder.Callback;
import fr.labri.macchiato.framework.business.model.product.Offer;
import fr.labri.macchiato.framework.business.model.product.Product;

/**
 * Callback used in the method
 * {@link ProjectService#getBestOffers(String, String, Callback)}
 * 
 * @author Matthieu FOUCAULT
 * 
 */
class ChooseOffersCallback extends Callback<Product> {

	private List<Product> products;
	private int requiredOfferNumber;
	private Callback<List<Product>> validateCallback;

	public ChooseOffersCallback(List<Offer> existingOffers,
			int requiredOfferNumber, Callback<List<Product>> callback) {
		super();

		this.products = new ArrayList<Product>();
		this.products.addAll(existingOffers);

		this.requiredOfferNumber = requiredOfferNumber;
		this.validateCallback = callback;
	}

	@Override
	public void onCallback(Product result) {

		if (!products.contains(result))
			products.add(result);
		else {
			for (Product p : products)
				if (p.equals(result))
					p.setQuantity(p.getQuantity() + result.getQuantity());
			requiredOfferNumber--;
		}

		if (products.size() == requiredOfferNumber) {
			validateCallback.onCallback(products);
		}

	}

}
